//
//  CYAddressBookTool.m
//  CreditAddressBook
//
//  Created by Lee on 15/9/16.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYAddressBookTool.h"
#import "RHPerson.h"
#import "CYABTool.h"
#import "CYContacts.h"
#import "CYTool.h"

static ABPeoplePickerNavigationController *_picker;
static BOOL _isEdit;
static CYABBloc _pickerBlock;
static ABNewPersonViewController *_new;
static CYABBloc _newBlock;
static CYBlock _personBlock;

#if IS_IOS9
static CNContactPickerViewController *_cnPicker;
static CNContactViewController *_contact;
static CYCNBlock _cnPickerBlock;
static CYCNBlock _cnNewBlock;
#endif

#if IS_IOS9
@interface CYAddressBookTool() <UINavigationControllerDelegate, ABPeoplePickerNavigationControllerDelegate, CNContactPickerDelegate, CNContactViewControllerDelegate, ABPersonViewControllerDelegate>
#else
@interface CYAddressBookTool() <UINavigationControllerDelegate, ABPeoplePickerNavigationControllerDelegate, ABNewPersonViewControllerDelegate, ABPersonViewController>
#endif

@end

@implementation CYAddressBookTool

#pragma mark - ios9前
+ (void)ABAddressBookUIPickerWithController:(UIViewController *)controller edit:(BOOL)isEdit completion:(CYABBloc)completion {
    _picker = [[ABPeoplePickerNavigationController alloc] init];
    _picker.peoplePickerDelegate = [self self];
    _isEdit = isEdit;
    _pickerBlock = [completion copy];
    [controller presentViewController:_picker animated:YES completion:nil];
}

#pragma mark - ABPeoplePickerNavigationController 代理
/**
 *  ios8前调用该方法
 */
+ (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
    [_picker dismissViewControllerAnimated:YES completion:nil];
    RHAddressBook *addressBook = [CYABTool addressBook];
    RHPerson *rhperson = [addressBook personForABRecordRef:person];
    
    dispatch_main_sync_safe_le(^{
        _pickerBlock(rhperson);
    });
    
    return _isEdit;
}

+ (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [_picker dismissViewControllerAnimated:YES completion:nil];
    _pickerBlock = nil;
}

/**
 *  ios8后调用该方法
 */
+ (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person {
    [_picker dismissViewControllerAnimated:YES completion:nil];
    RHAddressBook *addressBook = [CYABTool addressBook];
    RHPerson *rhperson = [addressBook personForABRecordRef:person];
    
    dispatch_main_sync_safe_le(^{
        _pickerBlock(rhperson);
    });
}

#pragma mark - ABUnknownPersonViewController
+ (void)ABUnknownPersonWithController:(UIViewController *)controller person:(RHPerson *)person edit:(BOOL)isEdit completion:(CYABBloc)completion {
    ABUnknownPersonViewController *unknown = [[ABUnknownPersonViewController alloc]init];
    unknown.displayedPerson = person.recordRef;
    unknown.allowsAddingToAddressBook = isEdit;//允许添加
    [controller.navigationController pushViewController:unknown animated:YES];
}

#pragma mark - ABNewPersonViewController
+ (void)ABNewPersonWithController:(UIViewController *)controller person:(RHPerson *)person completion:(CYABBloc)completion {
    ABNewPersonViewController *new = [[ABNewPersonViewController alloc] init];
    _new = new;
    new.newPersonViewDelegate = [self self];
    if (person) {
        new.displayedPerson = person.recordRef;
    }
    if (completion) {
        _newBlock = [completion copy];
    }
    
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:new];
    [controller presentViewController:navi animated:YES completion:nil];//使用该方法时出错
//    [controller.navigationController pushViewController:new animated:YES];
}

+ (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person {
    [_new dismissViewControllerAnimated:YES completion:nil];
    
    if (person) {
        RHAddressBook *addressBook = [CYABTool addressBook];
        RHPerson *rhperson = [addressBook personForABRecordRef:person];
        
        if (_newBlock) {
            dispatch_main_sync_safe_le(^{
                _newBlock(rhperson);
            });
        }
    }
    _newBlock = nil;
    
//    [_new.navigationController popViewControllerAnimated:YES];
}

+ (RHPerson *)newRHPersonWithName:(NSString *)name phones:(NSArray *)phones {
    RHAddressBook *ab = [CYABTool addressBook];
    RHPerson *newPerson  = [RHPerson newPersonInSource:[ab defaultSource]];
    
    if (phones) {
        RHMutableMultiStringValue *value = [[RHMutableMultiStringValue alloc] initWithType:kABMultiStringPropertyType];
        for (NSString *phone in phones) {
            [value addValue:phone withLabel:RHPersonPhoneIPhoneLabel];
        }
        newPerson.phoneNumbers = value;
    }
    if (name) {
        newPerson.lastName = name;
    }
    return newPerson;
}

#pragma mark - ios9后新框架ContactsUI与Contacts
#pragma mark - CNContactPickerViewController
#if IS_IOS9
+ (void)CNAddressBookUIPickerWithController:(UIViewController *)controller edit:(BOOL)isEdit completion:(CYCNBlock)completion {
    _cnPicker = [[CNContactPickerViewController alloc] init];
    _cnPicker.delegate = [self self];
    _isEdit = isEdit;
    if (completion) {
        _cnPickerBlock = [completion copy];
    }
    [controller presentViewController:_cnPicker animated:YES completion:nil];
}

+ (void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
    [_cnPicker dismissViewControllerAnimated:YES completion:nil];
}

+ (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    [_cnPicker dismissViewControllerAnimated:YES completion:nil];//注意此处的位置，否则后面会报错
    if (_cnPickerBlock) {
        _cnPickerBlock(contact);
    }
}

#pragma mark - CNContactViewController
+ (void)CNNewPersonWithController:(UIViewController *)controller person:(CNContact *)person completion:(CYCNBlock)completion {
    CNContactViewController *new = nil;
    if (person) {
        new = [CNContactViewController viewControllerForNewContact:person];
//        new.title = @"编辑联系人";
    } else {
        new = [CNContactViewController viewControllerForNewContact:person];
    }
    _contact = new;
    new.delegate = [self self];
    if (completion) {
        _cnNewBlock = [completion copy];
    }
    
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:new];
    [controller presentViewController:navi animated:YES completion:nil];
//    [controller.navigationController pushViewController:new animated:YES];
}

+ (void)contactViewController:(CNContactViewController *)viewController didCompleteWithContact:(nullable CNContact *)contact {
    [_contact dismissViewControllerAnimated:YES completion:nil];
    if (contact) {
        if (_cnNewBlock) {
            _cnNewBlock(contact);
        }
    }
//    [_contact popoverPresentationController];
}
#endif

#pragma mark - 方法
+ (void)addressBookUIPickerWithController:(UIViewController *)controller edit:(BOOL)isEdit completion:(CYBlock)completion {
    if (IOS9) {
        [self CNAddressBookUIPickerWithController:controller edit:isEdit completion:completion];
    } else {
        [self ABAddressBookUIPickerWithController:controller edit:isEdit completion:completion];
    }
}

+ (void)newPersonWithController:(UIViewController *)controller person:(CYContacts *)person completion:(CYBlock)completion {
    if (IOS9) {
        if (person) {
            [self CNNewPersonWithController:controller person:person.contact completion:completion];
        } else {
            [self CNNewPersonWithController:controller person:nil completion:completion];
        }
    } else {
        if (person) {
            [self ABNewPersonWithController:controller person:person.person completion:completion];
        } else {
            [self ABNewPersonWithController:controller person:nil completion:completion];
        }
    }
}

#pragma mark - ABPersonViewController
+ (void)ABPersonViewController:(UIViewController *)controller person:(RHPerson *)person completion:(CYBlock)completion {
    ABPersonViewController *personController = [[ABPersonViewController alloc]init];
    
    personController.displayedPerson = person.recordRef;
    //设置代理
    personController.personViewDelegate = [self self];
    if (completion) {
        _personBlock = [completion copy];
    }
    
    [personController setDisplayedPerson:person.recordRef];
    
    [personController setEditing:YES];
    
    [personController setAllowsActions:YES];
    
    [personController setAllowsEditing:YES];
    [controller.navigationController pushViewController:personController animated:YES];
}

+ (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    _personBlock([[CYABTool addressBook] personForABRecordRef:person]);
    return YES;
}

- (void)ABPersonViewController:(UIViewController *)controller person:(RHPerson *)person completion:(CYBlock)completion {
#if IS_IOS9
    
#else
#endif
    ABPersonViewController *personController = [[ABPersonViewController alloc] init];
    
    personController.displayedPerson = person.recordRef;
    //设置代理
    personController.personViewDelegate = self;
    if (completion) {
        _personBlock = [completion copy];
    }
    
    [personController setDisplayedPerson:person.recordRef];
    
    [personController setEditing:YES];
    
    [personController setAllowsActions:YES];
    
    [personController setAllowsEditing:YES];
//    [[personController editButtonItem].target performSelector:[personController editButtonItem].action];
//    SEL a = [personController editButtonItem].action;
//    [personController performSelector:a];
//    [CYTool addMethodWhthClass:[personController class] selector:@selector(setupEditing) targetClass:[self class] targetSelector:@selector(setupEditing)];
//    [personController performSelector:@selector(setupEditing)];
//    [CYTool swizzleWhthOriginalClass:[personController class] originalSEL:@selector(viewWillDisappear:) swizzledClass:[self class] swizzledSEL:@selector(hook_viewWillAppear:)];
    [CYTool addMethodWhthClass:[personController class] selector:@selector(addNavi) targetClass:[self class] targetSelector:@selector(addNavi)];
    [personController performSelector:@selector(addNavi)];
//    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:personController];
//    [controller presentViewController:navi animated:YES completion:nil];
    [controller.navigationController pushViewController:personController animated:YES];
}

- (void)hook_viewWillAppear:(BOOL)animation {
    if ([self isKindOfClass:NSClassFromString(@"ABPersonViewController_Modern")]) {
        ABPersonViewController *personController = (ABPersonViewController *)self;
        personController.editing = NO;
        [personController.view.window endEditing:YES];
//        SEL a = [personController editButtonItem].action;
        //        [personController performSelector:a];
//        personController.allowsEditing = YES;
//        [personController setEditing:YES animated:NO];
        //    [self hook_viewDidLoad];
        //    self.editing = YES;
        CYLog(@"运行ABPersonViewController");
    }
}

- (void)addNavi {
    //    [super viewDidLoad];
    ABPersonViewController *personController = (ABPersonViewController *)self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CYScreeSize.width, 64)];
    view.backgroundColor = CYNaviThemeColor;
    [personController.view addSubview:view];
    
//    personController.allowsEditing = YES;
    [personController setEditing:YES animated:NO];
}

- (void)setupEditing {
    ABPersonViewController *personController = (ABPersonViewController *)self;
    [personController setEditing:YES animated:YES];
    personController.allowsEditing = YES;
}

- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    _personBlock([[CYABTool addressBook] personForABRecordRef:person]);
    return YES;
}

@end
